<template>
  <el-drawer
    v-model="drawer"
    title="详情"
    :direction="direction"
    size="61%"
    class="drawer"
    destroy-on-close
  >
    <form-create
      v-model="formData"
      v-model:api="fapi"
      :rule="rule"
      :option="option"
      @submit="onSubmit"
    />
  </el-drawer>
</template>

<script lang="ts">
import { FormApi, FormTaskFillVO } from '@/api/system/form'

import formCreate from '@form-create/element-ui'
import { CommonStatusEnum } from '@/utils/constants'
import { ref, nextTick } from 'vue'

export default {
  name: 'SubmitForm',
  components: { formCreate: formCreate.$form() },
  setup() {
    const drawer = ref(false)
    const formLoading = ref(false)
    const formData = ref({})
    const fapi = ref(null)
    const rule = ref(null)
    const option = ref(null)
    const direction = 'rtl' // example direction
    const dffTaskId = ref()
    const submitData = ref({
      id: undefined,
      dffTaskId: undefined,
      dffFormId: undefined,
      dffFillData: undefined,
      dffFillWay: CommonStatusEnum.DISABLE,
      dffFillStatus: CommonStatusEnum.DISABLE,
      dffFormVersion: undefined,
      dffFillUserId: undefined,
      dffFillVersion: undefined
    })

    const open = async (id: number) => {
      formLoading.value = true
      try {
        if (id) {
          dffTaskId.value = id
          const data = await FormApi.getForm(id)
          if (data) {
            submitData.value.dffFormId = data.id
            submitData.value.dffFormVersion = data.dfReleaseVersion
            rule.value = formCreate.parseJson(data.dfFields)
            option.value = formCreate.parseJson(data.dfConf)
            await nextTick() // Ensure DOM updates
            data.dfData = {
              "Fcx7m00ona78abc": "11",
              "Fmtem00onbr0ahc": "11",
              "Fu9nm00onb0aaec": "11"
            }

            formData.value = (data.dfData)

            drawer.value = true
          }
        }
      } catch (error) {
        console.error('Failed to fetch form data:', error)
      } finally {
        formLoading.value = false
      }
    }

    const onSubmit = (formData: any) => {
      console.log('Form submitted:', formData)
      const data = submitData.value as unknown as FormTaskFillVO
      data.dffTaskId = dffTaskId.value
      data.dffFillData = formData
    }

    return { 
      drawer, 
      formLoading, 
      formData, 
      fapi, 
      rule, 
      option, 
      onSubmit, 
      open, 
      direction 
    }
  }
}
</script>
